package com.chaihu.front.controller.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chaihu.bean.enums.MsgCode;
import com.chaihu.bean.result.ResponseResult;
import com.chaihu.core.base.constants.CommonConstant;
import com.chaihu.core.base.controller.SuperController;
import com.chaihu.front.service.api.FrontService;
import com.chaihu.utils.exception.BaseException;
import com.chaihu.utils.util.DateUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping(path = "/app")
public class AppController extends SuperController {

    @Autowired
    private FrontService frontService;
    /**
     * 资源请求 get方式
     *
     * @param service 请求接口方式
     * @param request 请求对象 查询头信息 url等信息
     * @return http status 200 成功 其他失败
     */

    @RequestMapping(path = "/{service:.+}", method = RequestMethod.GET)
    @ApiOperation(value = "资源get请求", notes = "test: 返回 2XX 表示服务正常")
    @ApiImplicitParam(paramType = "query", name = "service", value = "用户编号", required = true, dataType = "String")
    public ResponseEntity<String> serviceGet(@PathVariable String service,
                                             HttpServletRequest request) {
        Map<String, String> headers = new HashMap<String, String>();
        Date startTime = DateUtil.getCurrentDate();
        ResponseEntity<String> responseEntity = null;
        try {
            this.getRequestInfo(request, headers);
            headers.put(CommonConstant.HTTP_SERVICE, service);
            headers.put(CommonConstant.HTTP_METHOD, CommonConstant.HTTP_METHOD_GET);
            log.debug("api：{} 请求报文为：{},header信息为：{}", "", headers);
            responseEntity = frontService.doApi(JSONObject.toJSONString(getParameterStringMap(request)), headers, request);
        } catch (BaseException e) {
            log.error("请求get 方法[" + service + "]失败：", e);
            responseEntity = new ResponseEntity<String>(JSONObject.toJSONString(e.getResult()), HttpStatus.OK);
        } catch (Throwable e) {
            log.error("请求get 方法[" + service + "]失败：", e);
            ResponseResult result = new ResponseResult(MsgCode.ERROR.getCode(), e.getMessage());
            responseEntity = new ResponseEntity<String>(JSON.toJSONString(result), HttpStatus.OK);
        }
        return responseEntity;
    }
}
